package com.java.controller;

import com.java.bean.Courier;
import com.java.bean.Message;
import com.java.mvc.ResponseBody;
import com.java.service.AdminService;
import com.java.util.CourierUtil;
import com.java.util.JSONUtil;
import com.java.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class AdminController {

    @ResponseBody("/admin/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){
        //1.    接参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2.    调用Service传参数，并获取结果
        boolean result = AdminService.login(username, password);
        //3.    根据结果，准备不同的返回数据
        Message msg = null;
        if(result){
            msg = new Message(0,"登录成功");
            //登录时间 和 ip的更新
            Date date = new Date();
            String ip = request.getRemoteAddr();
            AdminService.updateLoginAndIp(username,date,ip);
            request.getSession().setAttribute("adminUserName","username");
        }else if(username.equals("") || password.equals("")){
            msg = new Message(-1,"用户名或密码不能为空！");
        }else {
            msg = new Message(-1,"用户名或密码错误！");
        }

        //4.    将数据转换为JSON
        String json = JSONUtil.toJSON(msg);
        //5.    将JSON回复给ajax
        return json;
    }

    @ResponseBody("/admin/logout.do")
    public String logOut(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        session.removeAttribute("adminUserName");
        Message msg = new Message();
        msg.setStatus(0);
        msg.setResult("退出成功");
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/admin/adminName.do")
    public String adminName(HttpServletRequest request, HttpServletResponse response){
        String userName = UserUtil.getUserName(request.getSession());
        Message msg = new Message();
        msg.setStatus(0);
        msg.setResult("登录成功");
        msg.setData(userName);
        return JSONUtil.toJSON(msg);
    }


    @ResponseBody("/index/loginName.do")
    public String loginName(HttpServletRequest request, HttpServletResponse response){
        String userName = UserUtil.getUserName(request.getSession());
        String courierName = CourierUtil.getCourierName(request.getSession());
        Map<String,String> data = new HashMap<>();
        data.put("useName",userName);
        data.put("courierName",courierName);
        Message msg = new Message();
        msg.setStatus(0);
        msg.setData(data);
        return JSONUtil.toJSON(msg);
    }
}
